package com.siwei.mes.service.system.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.siwei.mes.common.base.BaseParams;
import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.MacTools;
import com.siwei.mes.controller.common.UploadController;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.erp.Rwdextra;
import com.siwei.mes.entity.erp.RwdextraExtend;
import com.siwei.mes.entity.erp.RwdextraInfo;
import com.siwei.mes.entity.excel.ImportCheckBatchConfigExcel;
import com.siwei.mes.entity.excel.ImportEquipmentExcel;
import com.siwei.mes.entity.excel.ImportKllzExcel;
import com.siwei.mes.entity.experiment.*;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteXnbgLlzhl;
import com.siwei.mes.entity.sync.tc.SupplyTask;
import com.siwei.mes.entity.sync.tc.Waybill;
import com.siwei.mes.entity.system.Equipment;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.enums.*;
import com.siwei.mes.mapper.ExperimentCheckWaybillWeekMapper;
import com.siwei.mes.mapper.ShxhSynchronizedataMapper;
import com.siwei.mes.mapper.erp.RwdextraExtendMapper;
import com.siwei.mes.mapper.experiment.*;
import com.siwei.mes.mapper.syncTc.SupplyTaskMapper;
import com.siwei.mes.mapper.syncTc.WaybillMapper;
import com.siwei.mes.mapper.system.EquipmentMapper;
import com.siwei.mes.mapper.system.TestProjectInfoMapper;
import com.siwei.mes.service.erp.RwdextraService;
import com.siwei.mes.service.experiment.ExperimentService;
import com.siwei.mes.service.system.DevopsService;
import com.siwei.mes.service.system.TestProjectInfoService;
import com.siwei.mes.sync.erp.service.impl.GenAbstractService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 运维工具接口
 *
 * @Description: 运维工具接口
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/17 19:14
 */
@Slf4j
@Service
public class DevopsServiceImpl implements DevopsService {
    @Value(value = "${excel.mac}")
    private String ADDRESS_MAC;
    @Value(value = "${excel.windows}")
    private String ADDRESS_WINDOWS;
    @Value(value = "${excel.linux}")
    private String ADDRESS_LINUX;
    @Value(value = "${server.port}")
    private String port;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private ExperimentSampleSmokeMapper experimentSampleSmokeMapper;
    @Resource
    private ExperimentSampleTakeMapper experimentSampleTakeMapper;
    @Resource
    private ExperimentWaybillMapper experimentWaybillMapper;
    @Resource
    private ExperimentSupplyTaskMapper experimentSupplyTaskMapper;
    @Resource
    private ExperimentItemorderMapper experimentItemorderMapper;
    @Resource
    private ExperimentTaskMapper experimentTaskMapper;
    @Resource
    private ExperimentQuickRecordMapper experimentQuickRecordMapper;
    @Resource
    private ExperimentBatchRecordMapper experimentBatchRecordMapper;
    @Resource
    private ExperimentMessageMapper experimentMessageMapper;
    @Resource
    private ExperimentPrintRecordMapper experimentPrintRecordMapper;
    @Resource
    private ExperimentCheckWaybillMapper experimentCheckWaybillMapper;
    @Resource
    private ExperimentCheckWaybillWeekMapper experimentCheckWaybillWeekMapper;
    @Resource
    private ExperimentCheckItemorderMapper experimentCheckItemorderMapper;
    @Resource
    private WaybillMapper waybillMapper;
    @Resource
    private RwdextraService rwdextraService;
    @Resource
    private ExperimentService experimentService;
    @Resource
    private RwdextraExtendMapper rwdextraExtendMapper;
    @Resource
    private GenAbstractService genAbstractService;
    @Resource
    private TestProjectInfoMapper testProjectInfoMapper;
    @Resource
    private ShxhSynchronizedataMapper shxhSynchronizedataMapper;
    @Resource
    private ExperimentGenConfigMapper experimentGenConfigMapper;
    @Resource
    private ExperimentYearConfigMapper experimentYearConfigMapper;
    @Resource
    private SupplyTaskMapper supplyTaskMapper;
    @Resource
    private EquipmentMapper equipmentMapper;
    @Resource
    private TestProjectInfoService testProjectInfoService;
    @Resource
    private CheckBatchConfigMapper checkBatchConfigMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearExperiment(Experiment experiment) {
        Long experimentId = experiment.getId();
        String experimentNo = experiment.getExperimentNo();
        Integer experimentType = experiment.getExperimentType();
        Integer checkType = experiment.getCheckType();

        log.info("开始清理试验委托信息，对应试验委托编号：【{}】，对应委托类型：【{}】", experimentNo, experimentType);
        log.info("清理的信息为：【{}】", JSON.toJSONString(experiment));
        this.clearExperimentInfo(experimentId, experimentType, checkType);

        experimentMapper.deleteByPrimaryKey(experimentId);
        log.info("清理试验委托信息完成，对应试验委托编号：【{}】，对应委托类型：【{}】", experimentNo, experimentType);
    }

    /**
     * 根据试验委托id  清空相关关联信息
     *
     * @param experimentId   试验委托id
     * @param experimentType 试验委托类型
     * @param checkType      1-快检 2-批检
     */
    private void clearExperimentInfo(Long experimentId, Integer experimentType, Integer checkType) {
        log.info("开始清空试验委托相关信息，对应试验委托id：【{}】，对应委托类型：【{}】，检测类型：【{}】", experimentId, experimentType, checkType);
        experimentDetailMapper.deleteByExperimentId(experimentId);
        experimentSampleSmokeMapper.deleteByExperimentId(experimentId);
        experimentSampleTakeMapper.deleteByExperimentId(experimentId);

        experimentMessageMapper.deleteByExperimentId(experimentId);
        experimentPrintRecordMapper.deleteByExperimentId(experimentId);
        /**判断是快检还是批检*/
        if (checkType.equals(CheckEnum.QUICK.getCode())) {
            experimentQuickRecordMapper.deleteByExperimentId(experimentId);
        } else {
            experimentBatchRecordMapper.deleteByExperimentId(experimentId);
        }
        /**判断是混凝土 还是原材料*/
        if (experimentType.equals(MaterialsEnum.CONCRETE.getCode())) {
            experimentItemorderMapper.deleteByExperimentId(experimentId);
            experimentTaskMapper.deleteByExperimentId(experimentId);
            experimentCheckItemorderMapper.deleteByExperimentId(experimentId);
        } else {
            List<Waybill> waybillList = experimentWaybillMapper.selectByExperimentId(experimentId);
            for (Waybill waybill : waybillList) {
                log.info("开始处理对应试验委托中所有运单对应代表数量，运单id：【{}】,代表数量：【{}】", waybill.getWaybillId(), waybill.getBehalfNumber());
                if (checkType.equals(CheckEnum.QUICK.getCode())) {
                    double genQuickQuantity = waybill.getGenQuickQuantity() == null ? 0 : waybill.getGenQuickQuantity().doubleValue();
                    waybill.setIsQuick(0);
                    if (genQuickQuantity - waybill.getBehalfNumber() > 0) {
                        waybill.setGenQuickQuantity(BigDecimal.valueOf(genQuickQuantity - waybill.getBehalfNumber()));
                    } else {
                        waybill.setGenQuickQuantity(BigDecimal.ZERO);
                    }
                } else {
                    double genBatchQuantity = waybill.getGenBatchQuantity() == null ? 0 : waybill.getGenBatchQuantity().doubleValue();
                    waybill.setIsBatch(0);
                    if (genBatchQuantity - waybill.getBehalfNumber() > 0) {
                        waybill.setGenBatchQuantity(BigDecimal.valueOf(genBatchQuantity - waybill.getBehalfNumber()));
                    } else {
                        waybill.setGenBatchQuantity(BigDecimal.ZERO);
                    }
                }
                waybillMapper.updateByPrimaryKeySelective(waybill);
            }
            experimentCheckWaybillWeekMapper.deleteByExperimentId(experimentId);
            log.info("开始清空experimentCheckWaybill表数据,devops工具方法，experimentId:【{}】", experimentId);
            experimentCheckWaybillMapper.deleteByExperimentId(experimentId);
            experimentWaybillMapper.deleteByExperimentId(experimentId);
            experimentSupplyTaskMapper.deleteByExperimentId(experimentId);
        }
    }

    /**
     * 根据服务类型获取磁盘路径
     * 默认是windows磁盘路径
     *
     * @return
     */
    public String getExcelPathName() {
        String operSystem = MacTools.getOperSystem();
        if (Arrays.stream(BaseParams.MAC_LIST).parallel().anyMatch(operSystem::contains)) {
            return ADDRESS_MAC;
        } else if (Arrays.stream(BaseParams.LINUX_LIST).parallel().anyMatch(operSystem::contains)) {
            return ADDRESS_LINUX;
        }
        return ADDRESS_WINDOWS;
    }

    @Override
    public String exportKllzExcel(HttpServletRequest request) {
        // 设置导出参数
        ExportParams exportParams = new ExportParams();

        List<ImportKllzExcel> list = new ArrayList<>();
        list.add(new ImportKllzExcel());
        // 执行导出
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ImportKllzExcel.class, list);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String str = "kllz" + sdf.format(new Date());

        /**获取盘符地址*/
        String pathName = getExcelPathName();
        String filePath = pathName + str + ".xlsx";
        String fileName = str + ".xlsx";
        //将excel 写入到服务器地址
        try {
            /**判断目录是否存在*/
            File saveFile = new File(pathName);
            if (!saveFile.exists()) {
                saveFile.mkdirs();
            }

            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();//关闭流

            /**获取可访问的excel地址*/
            String urlPath = UploadController.replacePathExcel(fileName, request, port);
            log.info("上传excel文件成功,路径：{},excel名称：{}", urlPath, fileName);

            return urlPath;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据导出失败" + e);
            return null;
        }
    }

    @Override
    public Map<String, Object> importKllzExcel(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(0); // 设置标题行，
        params.setHeadRows(1); // 设置表头行，

        List<ImportKllzExcel> dataList = new ArrayList<>();
        try {
            //读取excel 文件 转换至实体
            dataList = ExcelImportUtil.importExcel(file.getInputStream(), ImportKllzExcel.class, params);
        } catch (Exception e) {
            log.error("读取excel文件失败：" + e.getMessage(), e);
        }
        ExperimentGenConfig genConfig = experimentGenConfigMapper.selectOne(new ExperimentGenConfig()
                .setTestCode(TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode()).setExperimentType(MaterialsEnum.CONCRETE.getCode()));

        if (genConfig == null) {
            log.info("excel导入混凝土生成抗氯离子委托规则配置为空，暂不生成");
            return null;
        }

        int isProjectWithMix = genConfig.getIsProjectWithMix() == null ? 0 : genConfig.getIsProjectWithMix();
        int isYear = genConfig.getIsYear() == null ? 0 : genConfig.getIsYear();

        if (isProjectWithMix == 0 && isYear == 0) {
            log.info("混凝土{}生成委托规则配置未开启同工程同配合或限定未当年，暂不生成", genConfig.getTestName());
            return null;
        }

        Set<String> testProjectCodeList = new HashSet<>();
        testProjectCodeList.add(TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode());

        List<TestProjectInfo> testProjectInfoList = testProjectInfoMapper.selectByTestProjectCodeList(testProjectCodeList);

        int success = 0;
        int fail = 0;
        Set<Integer> failList = new HashSet<>();


        for (ImportKllzExcel dataObject : dataList) {
            try {
                log.info("开始处理对应excel数据，对应index：【{}】,对应excel数据：【{}】", dataObject.getIndex(), JSON.toJSONString(dataObject));
                String llzhl = dataObject.getLlzhl();

                if (llzhl == null) {
                    log.info("氯离子含量信息为空，直接跳过不处理，对应excel信息：【{}】", JSON.toJSONString(dataObject));
                    fail++;
                    failList.add(dataObject.getIndex());
                    continue;
                }
                String phbdh = dataObject.getPhbdh();
                if (StringUtils.isBlank(phbdh)) {
                    log.info("配合比编号为空，直接跳过不处理，对应excel信息：【{}】", JSON.toJSONString(dataObject));
                    fail++;
                    failList.add(dataObject.getIndex());
                    continue;
                }


                /**因为这里会录入百分号 这里需要默认乘以100*/
                Double llzhlDouble = Double.valueOf(llzhl);
                llzhl = String.valueOf(llzhlDouble * 100);
                log.info("最终乘以100的氯离子含量为：【{}】", llzhl);
                String rwdh = dataObject.getRwdh();
                if (rwdh == null) {
                    log.info("任务单信息为空，直接跳过不处理，对应excel信息：【{}】", JSON.toJSONString(dataObject));
                    fail++;
                    failList.add(dataObject.getIndex());
                    continue;
                }
                Rwdextra rwdextra = rwdextraService.selectByRwNo(rwdh);
                if (rwdextra == null) {
                    log.info("任务单信息不存在，直接跳过不处理，对应任务单编号：【{}】", rwdh);
                    fail++;
                    failList.add(dataObject.getIndex());
                    continue;
                }

                RwdextraInfo rwdextraInfo = rwdextra.getRwdextraInfo();
                String fGcmc = rwdextraInfo.getFGcmc();//工程名称

                /**这里获取当年对应的数据 是否有*/
                ExperimentYearConfig selectYearConfig = new ExperimentYearConfig().setExperimentType(MaterialsEnum.CONCRETE.getCode())
                        .setTestCode(genConfig.getTestCode()).setTestName(genConfig.getTestName());
                if (isProjectWithMix == 1) {
                    selectYearConfig.setGcmc(fGcmc);
                    selectYearConfig.setPhb(phbdh);

                    if (StringUtils.isBlank(fGcmc) || StringUtils.isBlank(phbdh)) {
                        log.info("excel导入混凝土生成抗氯离子对应工程名称或配合比为空，暂不生成！任务单：【{}】", rwdextra.getFrwdh());
                        fail++;
                        failList.add(dataObject.getIndex());
                        continue;
                    }
                }
                if (isYear == 1) {
                    selectYearConfig.setYearNo(DateHelper.getYear());
                }

                List<ExperimentYearConfig> yearConfigList = experimentYearConfigMapper.getList(selectYearConfig);
                ExperimentYearConfig yearConfig = null;
                if (!yearConfigList.isEmpty()) {
                    yearConfig = yearConfigList.get(0);
                }
                Long experimentId = null;
                log.info("查询当年对应数据是否存在，对应入参：【{}】", JSON.toJSONString(yearConfig));
                if (yearConfig == null) {
                    /**修改任务单扩展属性里面的氯离子含量*/
                    RwdextraExtend rwdextraExtend = rwdextra.getRwdextraExtend();
                    rwdextraExtend.setLlzHl(llzhl);
                    rwdextraExtendMapper.updateByPrimaryKeySelective(rwdextraExtend);

                    Experiment experiment = ImportKllzExcel.payloadExperimentInfo(dataObject);
                    experiment.setCreateType(CreateTypeEnum.EXCEL_CHECK.getCode()).setCreateCheckType(CheckTypeEnum.DEFAULT_CHECK.getCode());
                    experiment.setExperimentStatus(ExperimentStatusEnum.FINISH.getCode());
                    experiment.setBehalfNumber(rwdextra.getScquantity() != null ? rwdextra.getScquantity().doubleValue() : 0);
                    genAbstractService.payloadMaterialsInfo(dataObject.getQddj(), experiment);
                    experimentService.payloadOtherInfo(experiment, testProjectCodeList);
                    experimentMapper.insertSelective(experiment);

                    experimentId = experiment.getId();

                    ShxhSynchronizedata shxhInfo = shxhSynchronizedataMapper.selectByExperimentIdOne(experimentId);
                    if (shxhInfo == null) {
                        /**新增协会对应关系*/
                        ShxhSynchronizedata synchronizedata = new ShxhSynchronizedata().setSampleId(dataObject.getYpbh())
                                .setSampleNo(dataObject.getYpbh()).setConsignId(dataObject.getWtbh()).setExperimentId(experimentId)
                                .setFinistStatus("1");
                        shxhSynchronizedataMapper.insertSelective(synchronizedata);
                    } else {
                        shxhInfo.setSampleId(dataObject.getYpbh())
                                .setSampleNo(dataObject.getYpbh()).setConsignId(dataObject.getWtbh()).setExperimentId(experimentId)
                                .setFinistStatus("1");
                        shxhSynchronizedataMapper.updateByPrimaryKeySelective(shxhInfo);
                    }

                    /**新增试验委托详情*/
                    for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                        ExperimentDetail detail = new ExperimentDetail();
                        detail.setExperimentId(experiment.getId());
                        detail.setCheckType(CheckEnum.BATCH.getCode());
                        detail.erpInit(true);
                        detail.setTestProjectCode(testProjectInfo.getTestCode());
                        detail.setTestProjectName(testProjectInfo.getTestName());
                        detail.setObjJson(testProjectInfo.getObjJson());
                        if (testProjectInfo.getTestCode().equals(TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode())) {
                            ConcreteXnbgLlzhl concreteXnbgLlzhl = detail.getObjJson().toJavaObject(ConcreteXnbgLlzhl.class);
                            ConcreteXnbgLlzhl.SynInfo synInfo = concreteXnbgLlzhl.getSynInfo();
                            if (synInfo != null) {
                                synInfo.setLlzhl(llzhl);
                            }
                            detail.setObjJson(JsonUtils.beanToObject(concreteXnbgLlzhl));
                        }
                        experimentDetailMapper.insertSelective(detail);

                        /**新增对应快检的抽样信息  对应快检的所有的项目集合只有一条数据 */
                        ExperimentSampleSmoke sampleSmoke = new ExperimentSampleSmoke();
                        sampleSmoke.setId(null);
                        sampleSmoke.erpInit(true);
                        sampleSmoke.setExperimentId(experiment.getId());
                        sampleSmoke.setSampleTime(new Date());
                        sampleSmoke.setIsTestBlock(0);// 是否是试块 1-是 0-不是
                        sampleSmoke.setSamplePersonName(experiment.getEntrustPersonName());
                        sampleSmoke.setDisposerPersonName(experiment.getEntrustPersonName());
                        sampleSmoke.setTestProjectCode(testProjectInfo.getTestCode());
                        sampleSmoke.setTestProjectName(testProjectInfo.getTestName());
                        sampleSmoke.setSampleUse(testProjectInfo.getTestName());
                        experimentSampleSmokeMapper.insertSelective(sampleSmoke);
                    }

                    /**这里新增对应的当年数据*/
                    selectYearConfig.setId(null);
                    selectYearConfig.setExperimentId(experiment.getId());
                    selectYearConfig.setExperimentNo(experiment.getExperimentNo());
                    selectYearConfig.setCreateTime(new Date());
                    experimentYearConfigMapper.insertSelective(selectYearConfig);

                    log.info("导入excel生成抗氯离子成功，对应index：【{}】,对应试验委托id：【{}】,委托编号：【{}】", dataObject.getIndex(), experimentId, experiment.getExperimentNo());

                } else {
                    experimentId = yearConfig.getExperimentId();
                    log.info("导入excel生成抗氯离子成功，当前年存在数据，对应index：【{}】，试验委托id：[{}]", dataObject.getIndex(), experimentId);
                }
                /**插入试验台账对应小票数据和试验台账对应ERP任务单记录*/
                genAbstractService.insertExperimentRelatedRecords(experimentId, null, rwdextra.getFrwdh());
                success++;
            } catch (Exception e) {
                log.error("excel生成对应抗氯离子试验委托失败，对应excel信息：【{}】", JSON.toJSONString(dataObject));
                log.error("错误信息：【{}】", e.getMessage(), e);
                fail++;
                failList.add(dataObject.getIndex());
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", dataList.size());
        map.put("success", success);
        map.put("fail", fail);
        map.put("failList", failList);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteExperimentRel(String experimentNo, String supplyTaskCode, Long waybillId) {
        Experiment experiment = experimentMapper.selectByExperimentNo(experimentNo);
        assertTrue(experiment == null, "该试验委托信息未查询到，请确认是否正确");
        assertTrue(experiment.getExperimentType().equals(MaterialsEnum.CONCRETE.getCode()), "该运维接口暂不支持清空混凝土试验委托");


        Long experimentId = experiment.getId();

        if (StringUtils.isNotBlank(supplyTaskCode)) {
            SupplyTask supplyTask = supplyTaskMapper.selectBySupplyTaskCode(supplyTaskCode);
            if (supplyTask != null) {
                experimentSupplyTaskMapper.delete(new ExperimentSupplyTask().setExperimentId(experimentId).setSupplyTaskId(supplyTask.getId()));
            }
        }

        if (waybillId != null) {
            Waybill waybill = waybillMapper.selectByWid(waybillId);
            if (waybill != null) {
                experimentWaybillMapper.delete(new ExperimentWaybill().setExperimentId(experimentId).setWaybillId(waybill.getWaybillId()));

                /**修改这个试验台账的代表数量 == 所有跟这个试验台账相关的运单签收数量之和*/
                List<Waybill> waybillList = experimentWaybillMapper.selectByExperimentId(experimentId);
                Double behalfNumberSum = null;
                if (!waybillList.isEmpty()) {
                    behalfNumberSum = waybillList.stream().map(Waybill::getBehalfNumber).reduce((double) 0, Double::sum);
                    Experiment updateExperiment = new Experiment();
                    updateExperiment.setId(experimentId);
                    updateExperiment.setBehalfNumber(behalfNumberSum);
                    updateExperiment.tcInit(false);
                    experimentMapper.updateByPrimaryKeySelective(updateExperiment);
                }
            }
        }
    }

    @Override
    public void insertExperimentRel(String experimentNo, String supplyTaskCode, Long waybillId) {
        Experiment experiment = experimentMapper.selectByExperimentNo(experimentNo);
        assertTrue(experiment == null, "该试验委托信息未查询到，请确认是否正确");
        assertTrue(experiment.getExperimentType().equals(MaterialsEnum.CONCRETE.getCode()), "该运维接口暂不支持清空混凝土试验委托");


        Long experimentId = experiment.getId();

        if (StringUtils.isNotBlank(supplyTaskCode)) {
            SupplyTask supplyTask = supplyTaskMapper.selectBySupplyTaskCode(supplyTaskCode);
            if (supplyTask != null) {
                /**快检/批检与试验台账和供货任务的关系*/
                ExperimentSupplyTask experimentSupplyTask = new ExperimentSupplyTask()
                        .setExperimentId(experimentId)
                        .setSupplyTaskId(supplyTask.getId());
                if (experimentSupplyTaskMapper.selectOne(experimentSupplyTask) == null) {
                    experimentSupplyTask.setCreateTime(new Date());
                    experimentSupplyTask.setReadTime(null);
                    experimentSupplyTaskMapper.insertSelective(experimentSupplyTask);

                    /**这里新增任务单的关联关系 给对应试验委托的isNewTask改为1*/
                    log.info(this.getClass().getName() + "新增任务单给对应isNewTask修改为1");
                    experimentMapper.updateIsNewTask(experimentId, 1);
                }
            }
        }

        if (waybillId != null) {
            Waybill waybill = waybillMapper.selectByWid(waybillId);
            if (waybill != null) {
                /**快检/批检与试验台账和运单的关系*/
                ExperimentWaybill experimentWaybill = new ExperimentWaybill()
                        .setExperimentId(experimentId)
                        .setWaybillId(waybillId)
                        .setBehalfNumber(waybill.getSignQuantity() == null ? 0 : waybill.getSignQuantity().doubleValue());
                experimentWaybillMapper.insertSelective(experimentWaybill);

                /**修改这个试验台账的代表数量 == 所有跟这个试验台账相关的运单签收数量之和*/
                List<Waybill> waybillList = experimentWaybillMapper.selectByExperimentId(experimentId);
                Double behalfNumberSum = null;
                if (!waybillList.isEmpty()) {
                    behalfNumberSum = waybillList.stream().map(Waybill::getBehalfNumber).reduce((double) 0, Double::sum);
                    Experiment updateExperiment = new Experiment();
                    updateExperiment.setId(experimentId);
                    updateExperiment.setBehalfNumber(behalfNumberSum);
                    updateExperiment.tcInit(false);
                    experimentMapper.updateByPrimaryKeySelective(updateExperiment);
                }
            }
        }
    }

    @Override
    public String exportEquipmentExcel(HttpServletRequest request) {
        // 设置导出参数
        ExportParams exportParams = new ExportParams();

        List<ImportEquipmentExcel> list = new ArrayList<>();
        list.add(new ImportEquipmentExcel());
        // 执行导出
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ImportEquipmentExcel.class, list);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String str = "equipment_" + sdf.format(new Date());

        /**获取盘符地址*/
        String pathName = getExcelPathName();
        String filePath = pathName + str + ".xlsx";
        String fileName = str + ".xlsx";
        //将excel 写入到服务器地址
        try {
            /**判断目录是否存在*/
            File saveFile = new File(pathName);
            if (!saveFile.exists()) {
                saveFile.mkdirs();
            }

            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();//关闭流

            /**获取可访问的excel地址*/
            String urlPath = UploadController.replacePathExcel(fileName, request, port);
            log.info("上传excel文件成功,路径：{},excel名称：{}", urlPath, fileName);

            return urlPath;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据导出失败" + e);
            return null;
        }
    }

    @Override
    public Map<String, Object> importEquipmentExcel(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(0); // 设置标题行，
        params.setHeadRows(1); // 设置表头行，

        List<ImportEquipmentExcel> dataList = new ArrayList<>();
        try {
            //读取excel 文件 转换至实体
            dataList = ExcelImportUtil.importExcel(file.getInputStream(), ImportEquipmentExcel.class, params);
        } catch (Exception e) {
            log.error("读取excel文件失败：" + e.getMessage());
        }

        int success = 0;
        int fail = 0;
        Set<String> failList = new HashSet<>();

        for (ImportEquipmentExcel equipmentExcel : dataList) {
            log.info("开始处理仪器设备对应excel数据，对应设备编号：【{}】,对应excel数据：【{}】", equipmentExcel.getEquipmentNo(), JSON.toJSONString(equipmentExcel));
            try {
                String equipmentNo = equipmentExcel.getEquipmentNo();
                if (StringUtils.isNotBlank(equipmentNo)) {
                    Equipment entity = ImportEquipmentExcel.payloadEquipmentInfo(equipmentExcel);
                    equipmentMapper.insertSelective(entity);
                    success++;
                } else {
                    fail++;
                    failList.add(equipmentNo);
                }
            } catch (Exception e) {
                log.error("excel导入对应设备信息失败，对应excel信息：【{}】", JSON.toJSONString(equipmentExcel));
                log.error("错误信息：【{}】", e.getMessage(), e);
                fail++;
                failList.add(equipmentExcel.getEquipmentNo());
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", dataList.size());
        map.put("success", success);
        map.put("fail", fail);
        map.put("failList", failList);
        return map;
    }

    @Override
    public String exportCheckBatchConfigExcel(HttpServletRequest request) {
        // 设置导出参数
        ExportParams exportParams = new ExportParams();

        List<ImportCheckBatchConfigExcel> list = new ArrayList<>();
        list.add(new ImportCheckBatchConfigExcel());
        // 执行导出
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ImportCheckBatchConfigExcel.class, list);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String str = "checkBatchConfig_" + sdf.format(new Date());

        /**获取盘符地址*/
        String pathName = getExcelPathName();
        String filePath = pathName + str + ".xlsx";
        String fileName = str + ".xlsx";
        //将excel 写入到服务器地址
        try {
            /**判断目录是否存在*/
            File saveFile = new File(pathName);
            if (!saveFile.exists()) {
                saveFile.mkdirs();
            }

            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();//关闭流

            /**获取可访问的excel地址*/
            String urlPath = UploadController.replacePathExcel(fileName, request, port);
            log.info("上传excel文件成功,路径：{},excel名称：{}", urlPath, fileName);

            return urlPath;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据导出失败" + e);
            return null;
        }
    }

    @Override
    public Map<String, Object> importCheckBatchConfigExcel(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(0); // 设置标题行，
        params.setHeadRows(1); // 设置表头行，

        List<ImportCheckBatchConfigExcel> dataList = new ArrayList<>();
        try {
            //读取excel 文件 转换至实体
            dataList = ExcelImportUtil.importExcel(file.getInputStream(), ImportCheckBatchConfigExcel.class, params);
        } catch (Exception e) {
            log.error("读取excel文件失败：" + e.getMessage());
        }

        int success = 0;
        int fail = 0;
        Set<String> failList = new HashSet<>();

        Map<String, TestProjectInfo> testProjectInfoMap = testProjectInfoService.getAllTestProjectInfo();

        for (ImportCheckBatchConfigExcel batchConfigExcel : dataList) {
            log.info("开始处理对应批检指标配置excel数据，对应excel数据：【{}】", JSON.toJSONString(batchConfigExcel));
            try {
                String projectCategory = batchConfigExcel.getProjectCategory();
                if (StringUtils.isBlank(projectCategory)) {
                    log.info("物料类型为空，直接跳过不处理，对应excel信息：【{}】", JSON.toJSONString(batchConfigExcel));
                    fail++;
                    failList.add(batchConfigExcel.getTestProjectName());
                    continue;
                }
                String testProjectName = batchConfigExcel.getTestProjectName();
                if (StringUtils.isBlank(testProjectName)) {
                    log.info("试验项目名称为空，直接跳过不处理，对应excel信息：【{}】", JSON.toJSONString(batchConfigExcel));
                    fail++;
                    failList.add(batchConfigExcel.getTestProjectName());
                    continue;
                }

                String checkType = batchConfigExcel.getCheckType();
                if (StringUtils.isBlank(checkType)) {
                    log.info("检验类型为空，直接跳过不处理，对应excel信息：【{}】", JSON.toJSONString(batchConfigExcel));
                    fail++;
                    failList.add(batchConfigExcel.getTestProjectName());
                    continue;
                }

                MaterialsEnum materialsEnum = MaterialsEnum.selectByCode(Integer.valueOf(projectCategory));
                if (materialsEnum == null) {
                    log.info("物料类型不存在，直接跳过不处理，对应excel信息：【{}】", JSON.toJSONString(batchConfigExcel));
                    fail++;
                    failList.add(batchConfigExcel.getTestProjectName());
                    continue;
                }
                String mapKey = materialsEnum.getTestProjectType() + "_" + testProjectName;
                TestProjectInfo testProjectInfo = testProjectInfoMap.get(mapKey);
                if (testProjectInfo == null) {
                    log.info("试验项目不存在，直接跳过不处理，对应excel信息：【{}】", JSON.toJSONString(batchConfigExcel));
                    fail++;
                    failList.add(batchConfigExcel.getTestProjectName());
                    continue;
                }

                CheckBatchConfig entity = ImportCheckBatchConfigExcel.payloadCheckBatchConfigInfo(batchConfigExcel, testProjectInfo);
                checkBatchConfigMapper.insertSelective(entity);
                success++;
            } catch (Exception e) {
                log.error("excel导入对应批次配置信息失败，对应excel信息：【{}】", JSON.toJSONString(batchConfigExcel));
                log.error("错误信息：【{}】", e.getMessage(), e);
                fail++;
                failList.add(batchConfigExcel.getTestProjectName());
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", dataList.size());
        map.put("success", success);
        map.put("fail", fail);
        map.put("failList", failList);
        return map;
    }
}
